package com.ruoyi.quartz.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.db.domain.FormInfoPushRecord;
import com.ruoyi.form.service.IFormInfoPushRecordService;
import com.ruoyi.market.http.service.MarketApiService;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.bouncycastle.asn1.dvcs.TargetEtcChain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * api 推送任务查询
 * 
 * @author ruoyi
 */
@Component("formPushTask")
public class FormPushTask
{

    // api 推送缓存的计时器 名称
    private static String FORM_PUSH_TIMING_CACHE_NAME = "FORM_PUSH_TIMING_CACHE_NAME";

    private static String CACHE_KEY = "timeSecond";

    // 每次时间递增的时长
    // 任务的执行时长
    private static Long TIME_ADDUP_SECOND = 10L;

    @Autowired
    private EhCacheManager ehCacheManager;
    @Autowired
    IFormInfoPushRecordService formInfoPushRecordService;
    @Autowired
    MarketApiService marketApiService;


    public void taskFun()
    {
        asdfas();
    }

    public void asdfas(){

        String nowDate = LocalDate.now().toString();
        String nowTime = DateUtils.getTime();

        // 查询今日，当前时间
        // 待执行或者正在执行的 任务
        List<FormInfoPushRecord> pushRecordList = formInfoPushRecordService.selectPushTaskPushRecordList(nowDate, nowTime);

        Cache<String, Long> testCache = ehCacheManager.getCache(FORM_PUSH_TIMING_CACHE_NAME);
        Long timeSecond = testCache.get(CACHE_KEY);

        // 获取计时器的值
        if (ObjectUtil.isEmpty(timeSecond) || timeSecond > (Long.MAX_VALUE - 1000)){
            timeSecond = 0L;
        }

        //缓存计时器的值
        Long newTimeSecond = timeSecond + TIME_ADDUP_SECOND;
        testCache.put(CACHE_KEY, newTimeSecond);

        // 可执行的任务ID
        List<String> recordIdList = new ArrayList<>();
        for (FormInfoPushRecord formInfoPushRecord : pushRecordList) {
            Long pushSpace = formInfoPushRecord.getPushSpace();
            if (timeSecond%pushSpace == 0){
                // 可以执行
                recordIdList.add(String.valueOf(formInfoPushRecord.getId()));
            }
        }

        if (CollUtil.isNotEmpty(recordIdList)){
            marketApiService.pushData(recordIdList);
        }
    }

}
